//
//  XMLModel.swift
//  ShiZhe
//
//  Created by 陈卿伟 on 16/9/1.
//  Copyright © 2016年 陈卿伟. All rights reserved.
//

import UIKit

class XMLModel: NSObject {
    var selecte1:Int
    var selecte2:Int
    
    var doc:GDataXMLDocument!
    
    init(selecteRow1:Int,selecteRow2:Int) {
        //获取xml文件路径
        let path = NSBundle.mainBundle().pathForResource("province_data", ofType:"xml")
        //获取xml文件内容
        let xmlData = NSData(contentsOfURL: NSURL(fileURLWithPath: path!))
        //这里的语法已经把OC的初始化函数直接转换过来了
        let doc:GDataXMLDocument = try! GDataXMLDocument(data:xmlData, options : 0)
        self.doc = doc
        
        self.selecte1 = selecteRow1
        self.selecte2 = selecteRow2
    }
    
    //计算长度
    func analysisXMLCount(table:Int)->Int{
        let step1 = try! doc.nodesForXPath("//province", namespaces:nil) as! [GDataXMLElement]
        let step2 = step1[selecte1].elementsForName("city") as! [GDataXMLElement]
        let step3 = step2[selecte2].elementsForName("district") as! [GDataXMLElement]
        switch table {
        case 1:
            return step1.count
        case 2:
            return step2.count
        case 3:
            return step3.count
        default:
            return 0
        }
    }
    
    //解析xml
    func analysisXML(table:Int,row:Int)->String{
        //通过XPath方式获取root节点下的所有province节点，在路径复杂时特别方便
        let step1 = try! doc.nodesForXPath("//province", namespaces:nil) as! [GDataXMLElement]
        let step2 = step1[selecte1].elementsForName("city") as! [GDataXMLElement]
        let step3 = step2[selecte2].elementsForName("district") as! [GDataXMLElement]
        switch table {
        case 1:
            let step1String = step1[row].attributeForName("name").stringValue()
            return step1String!
        case 2:
            let step2String = step2[row].attributeForName("name").stringValue()
            return step2String!
        case 3:
            let step3String = step3[row].attributeForName("name").stringValue()
            return step3String!
        default:
            return ""
        }
    }
}





























//        for province in provinces {
//            //省的id属性
//            let uid = province.attributeForName("id").stringValue()
//            //获取city节点元素
//            let cityElement = province.elementsForName("city")[0] as! GDataXMLElement
//            //获取city子节点的name属性
//            let uname = cityElement.attributeForName("name").stringValue()
//            //获取city节点下district节点
//            let districtElement = (cityElement.elementsForName("district")[0]
//                as! GDataXMLElement)
//            //获取district节点下的name属性
//            let district = districtElement.attributeForName("name").stringValue()
//            //输出调试信息
//            print("User: uid:\(uid),uname:\(uname),district:\(district)")
//        }
